<template>
  <div class="page">

    <div ref="tableHeaderContainer" class="base-search-group-container">

      <form class="base-search" onsubmit="return false;">
        <div class="customer-list-base-search-group top-btn-group" style="width: auto;">
          <el-button class="repertory-chart-button" type="primary" @click="openStock($event);trackEventHandler('stockTable')" v-if="viewReport">
            <i class="iconfont icon-depot task-font14"></i>
            {{ $t('common.pageTitle.pageStatsPart') }}
          </el-button>

          <el-select v-if="isShowRepertorySelect" :value="repertoryName" filterable @input="chooseRepertory($event);trackEventHandler('chooseRepertory')" class="srp-list-form-item">
            <el-option value="" :label="$t('report.part.title37')"></el-option>
            <el-option v-for="item in visibleRepertories" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
          
          <el-radio-group v-model="model.isMissingPart" @change="loadData('changeTab');trackEventHandler('switchPart')" v-if="manageRepertories" style="position: relative;top: 1px">
            <el-radio-button :label="0">{{$t('part.text64')}}</el-radio-button>
            <el-radio-button :label="1">{{$t('part.components.partStock.text2')}}</el-radio-button>
          </el-radio-group>
        </div>
        <div class="base-search-right flex-x">
          <div class="input-with-append-search">
            <el-input v-model="model.keyWord" :placeholder="$t('common.form.preview.subSparePart.pla2')" v-trim:blur>
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button slot="append" type='primary' @click="model.pageNum=1;search();trackEventHandler('search')" native-type="submit" v-track="$track.formatParams('KEYWORD_SEARCH')">{{ $t('common.base.search') }}</el-button>
            </el-input>
          </div>
          <el-button type="plain-third" @click="reset();trackEventHandler('reset')" class="ml_12" v-track="$track.formatParams('RESET_SEARCH')">
            {{$t('common.base.reset')}}
          </el-button>
          <div class="advanced-search-visible-btn ml_12" @click.stop="isExpand = !isExpand;trackEventHandler('advSearch')">
            <i class="iconfont icon-filter"></i>
            {{$t('common.base.advancedSearch')}}
          </div>
        </div>
      </form>
    </div>

    <base-search-drawer
      :show='isExpand'
      @close='closeDrawer'
      @reset='reset'
      @search='search'
      :show-setting='false'
    >
      <el-form>
        <el-form-item :label="$t('common.fields.partName.displayName')">
          <el-select popper-class="common-advance-popper" style="width: 100%;"
                        :placeholder="$t('common.form.preview.subSparePart.title2')"
                        :value="sparepart.sparepartId"
                        @input="chooseSparepart"
                        filterable
                        clearable
                        remote
                        :remote-method="fetchSparepart"
                        :loading="sparepart.loading">

            <el-option
              v-for="item in sparepart.options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <div class="part-option">
                <p>{{$t('common.label.serialNumber')}}{{item.serialNumber}}</p>
                <p>{{$t('common.base.name')}}{{item.name}}</p>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.label.sparepartType')">
          <el-select :placeholder="$t('part.list.text7')" v-model="model.type">
            <el-option :label="$t('projectManage.setting.authSetting.all')" value=""></el-option>
            <el-option :label="item" :value="item" v-for="item in types" :key="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.part.specifications')">
          <el-input v-model="model.standard " :placeholder="$t('common.placeholder.input2')" maxlength="1000"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.label.explain')">
          <el-input v-model="model.description" :placeholder="$t('common.placeholder.input2')" maxlength="1000"></el-input>
        </el-form-item>
        <el-form-item :label="$t('part.text74')">
          <el-select v-model="model.repertoryTypeList" :placeholder="$t('common.placeholder.select')" multiple>
            <el-option value="备件库" :lable="$t('sparepart.setting.repertory.label4')"></el-option>
            <el-option value="不良品库" :lable="$t('sparepart.setting.repertory.label5')"></el-option>
            <el-option value="区域库" :lable="$t('sparepart.setting.repertory.label6')"></el-option>
            <el-option value="备件其他库" :lable="$t('sparepart.setting.repertory.label7')"></el-option>
          </el-select>
        </el-form-item>
        <!--关联产品类型：超级二维码开启并且持有备件和使用记录有-->
        <template v-if="openSuperCodePro">
          <el-form-item :label="$t('common.label.ralationProductType')">
            <el-select :placeholder="$t('part.list.text11')" v-model="model.productTypeList" multiple filterable>
              <el-option :label="item.catalogName" :value="item.id" v-for="item in productType" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>
    </base-search-drawer>

    <div ref="tableDoContainer" class="base-operation-bar-container" style="border: none">
      <div class="action-button-group-left top-btn-group">
        <el-button v-if="allowInout" type="primary" @click="btnToBatchOperate('batchOutStock');trackEventHandler('outStock')" native-type="submit">{{ $t('common.pageTitle.pageLeavestockList') }}</el-button>
        <el-button v-if="allowInout" type="primary" @click="btnToBatchOperate('batchInStock');trackEventHandler('inStock')" native-type="submit">{{ $t('common.form.preview.sparepart.inStock') }}</el-button>
        <el-button v-if="allowInout && isShowPartTransfer" type="primary" @click="btnToBatchOperate('batchTransfer');trackEventHandler('transfer')" native-type="submit">{{$t('common.pageTitle.pageAllocatestockList')}}</el-button>
        <el-button v-if="allowInout && isPersonalRepertory !== false && isShowMoreSperaParts" type="primary" @click="btnToBatchOperate('batchSpare');trackEventHandler('spare')" native-type="submit">{{ $t('common.event.actionStatus.allot') }}</el-button>
        <el-button v-if="allowInout" type="primary" @click="openDialogForSetSafetyStock(selected);trackEventHandler('setSafeStock')" native-type="submit">{{ $t('part.text65') }}</el-button>
        <el-button class="dark-btn" v-if="allowEdit" type="plain-third" @click="removestockBatch($event);trackEventHandler('remove')">
          <i class="iconfont icon-delete task-font14"></i>
          {{ $t('common.base.remove') }}
        </el-button>
      </div>
      <div class="action-button-group-right">
        <el-dropdown trigger="click" :show-timeout="150" v-if="(isAllowExport || isAllowImport) && !model.isMissingPart">
          <span class="el-dropdown-link cur-point mr_12">
            {{ $t('common.base.moreOperator') }}
            <i class="iconfont icon-more"></i>
          </span>

          <el-dropdown-menu slot="dropdown" class="dropdown-more">
            
            <el-dropdown-item v-if="isAllowImport">
              <span class="dropdown-item" @click="importStock" v-track="$track.formatParams('IMPORT_PART', null, 'MORE_ACTIONS')">{{ $t('common.base.importPart') }}</span>
            </el-dropdown-item>
            
            <el-dropdown-item v-if="isAllowExport">
              <span class="dropdown-item" @click="exportData(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{ $t('common.base.export') }}</span>
            </el-dropdown-item>
            
            <el-dropdown-item v-if="isAllowExport">
              <span class="dropdown-item" @click="exportData(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{ $t('common.base.exportAll') }}</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-dropdown :hide-on-click="false" trigger="click" :show-timeout="150" v-track="$track.formatParams('SELECT_COLUMN')">
          <span class="el-dropdown-link cur-point ml_12">
            {{$t('common.base.choiceCol')}}
            <i class="iconfont icon-more"></i>
          </span>
          

          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-for="column in filterColumns" :key="column.field">
              <el-checkbox :value="column.show" @input="chooseColnum(column)">{{column.label}}</el-checkbox>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <!-- <div ref="BaseSelectionBarComponent" class="base-selection-wrapper">
      <base-selection-bar ref="baseSelectionBar" v-model="selected" @toggle-selection="toggleSelection" @show-panel="() => multipleSelectionPanelShow = true" />
    </div> -->


    <div class="table-container">
      <el-table stripe ref="table"
                   v-table-style
                   v-loading="pageLoading"
                   border
                   :height="tableContainerHeight"
                   class="bbx-normal-list-box"
                   :data="page.list"
                   header-row-class-name="base-table-header-v3"
                   @select="handleSelection"
                   @select-all="handleSelection"
                   @sort-change="sort">
        <template slot="empty">
          <BaseListForNoData v-show="!pageLoading"></BaseListForNoData>
        </template>
        <el-table-column
          type="selection"
          align='center'
          fixed
          width="44">
        </el-table-column>

        <el-table-column v-for="column in columns" :key="column.field"
                            v-if="column.show"
                            :label="column.label"
                            :width="column.width"
                            :prop="column.field"
                            :sortable="column.sortable"
                            :class-name="column.field == 'serialNumber' ? 'part-name-superscript-td' : ''"
                            :fixed="column.fixed"
                            :show-overflow-tooltip="column.tooltip && column.field !== 'serialNumber'">

          <template slot-scope="scope" style="position: relative;">

            <template v-if="column.field == 'serialNumber'">

              <template v-if="scope.row.sparepart">
                <span
                  @click="openPartInfoDialog(scope.row.sparepart)"
                  type="text"
                  class="table-whitelist table-primary"
                  :class="scope.row.isGuideData ? column.className : ''"
                >
                  {{scope.row.sparepart.serialNumber}}
                  <el-tag v-if="(scope.row.safetyStock !== null) && scope.row.safetyStock >= scope.row.repertoryCount" size="mini" type="danger">
                    {{ $t('part.components.partStock.text2') }}
                  </el-tag>
                </span>
              </template>
            </template>
            <template v-else-if="column.field == 'name'">
              <template v-if="scope.row.sparepart">{{scope.row.sparepart && scope.row.sparepart.name}}</template>
            </template>
            <template v-else-if="column.field == 'type'">
              <template v-if="scope.row.sparepart">{{scope.row.sparepart.type}}</template>
            </template>
            <template v-else-if="column.field == 'standard'">
              <template v-if="scope.row.sparepart">{{scope.row.sparepart.standard}}</template>
            </template>
            <template v-else-if="column.field == 'repertory'">
              <template v-if="scope.row.repertory">{{scope.row.repertory.name}}</template>
            </template>
            <template v-else-if="column.field == 'repertoryType'">
              <template v-if="scope.row.repertory">{{scope.row.repertory.type}}</template>
            </template>
            <template v-else-if="column.field == 'operate'" slot-scope="scope">
              <el-button type="text" class="no-padding" size="medium" @click="btnToSingleOperate('outStock', scope.row);tableTrackEventHandler('outStock')" v-if="isEnableSparePart(scope.row) && allowInout && allowInOutStore(scope.row)">{{ $t('common.pageTitle.pageLeavestockList') }}</el-button>
              <el-button type="text" class="no-padding" size="medium" @click="btnToSingleOperate('inStock', scope.row);tableTrackEventHandler('inStock')" v-if="isEnableSparePart(scope.row) && allowInout && allowInOutStore(scope.row)">{{ $t('common.form.preview.sparepart.inStock') }}</el-button>
              <el-button type="text" class="no-padding" size="medium" @click="btnToSingleOperate('allocation', scope.row);tableTrackEventHandler('allocation')" v-if="isEnableSparePart(scope.row) && allowInout && allowInOutStore(scope.row) && isShowPartTransfer">{{ $t('common.form.preview.sparepart.allocatestock') }}</el-button>
              <el-button type="text" class="no-padding" size="medium" @click="btnToSingleOperate('spare', scope.row);tableTrackEventHandler('spare')" v-if="isEnableSparePart(scope.row) && allowInout && allowInOutStore(scope.row) && isPersonalRepertory !== false && isShowMoreSperaParts">{{ $t('common.base.distribution') }}</el-button>
              <el-button type="text" class="no-padding" size="medium" @click="btnToSingleOperate('apply', scope.row);tableTrackEventHandler('apply')" v-if="isEnableSparePart(scope.row) && allowApply && isShowPartApply">{{ $t('part.tips72') }}</el-button>
            </template>
            <template v-else-if="column.field == 'unit'">
              <template v-if="scope.row.sparepart">{{scope.row.sparepart.unit}}</template>
            </template>
            <template v-else-if="column.field == 'description'">
              <template v-if="scope.row.sparepart">{{scope.row.sparepart.description}}</template>
            </template>
            <!--关联产品类型-->
            <template v-else-if="column.field == 'productTypeList'">
              <div v-if="scope.row.productTypeList && scope.row.productTypeList.length!=0">
                <label
                  style="color: #55B7B4;cursor: pointer"
                  v-for="(item, index) in scope.row.productTypeList"
                  :key="`${index}_${scope.row.id}`"
                  @click="openProductMenuTab(item.id)">
                  {{ item.catalogName }}<span v-if="index!=scope.row.productTypeList.length-1">,</span>
                </label>
              </div>
            </template>
            <template v-else>
              {{scope.row[column.field]}}
            </template>
          </template>

        </el-table-column>
      </el-table>
    </div>

    <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer">
      <div class="list-info">
        <i18n path="common.base.table.totalCount">
          <span place="count" class="level-padding">{{page.total || 0}}</span>
        </i18n>
        <i18n path="common.base.table.selectedNth">
          <span
            place="count"
            class="base-table-selected-count"
            @click="multipleSelectionPanelShow = true"
          >{{selected.length}}</span>
        </i18n>
        <template v-if="selected&&selected.length>0">
          <span class="base-table-selected-count" @click="toggleSelection()">{{ $t('common.base.clear') }}</span>
        </template>
      </div>
      <el-pagination
        class="customer-table-pagination"
        background
        @current-change="jump"
        @size-change="pageSizeChange"
        :page-sizes="defaultTableData.defaultPageSizes"
        :page-size="model.pageSize"
        :current-page="model.pageNum"
        layout="prev, pager, next, sizes, jumper"
        :total="page.total">
      </el-pagination>
    </div>


    <div class="page-panel">
      <!-- 批量 出库/入库/调拨/分配 -->
      <stock-batch-opt-dialog
        ref="stockBatchOptDialog"
        :dialog-visible="batchOptDialogVisible"
        :type="batchOptType"
        :repertories="batchOptRepertories"
        :repertory="batchOptRepertory"
        :sparepart-config="sparepartConfig"
        @success="initialize"
        @close="batchOptDialogVisible=false"
      ></stock-batch-opt-dialog>

      <!-- 单个 出库/入库/调拨/分配/申领 -->
      <stock-single-opt-dialog
        ref="stockSingleOptDialog"
        :dialog-visible="singleOptDialogVisible"
        :type="singleOptType"
        :formdata="formdata"
        :repertories="repertories"
        :repertory="manageRepertories"
        :sparepart-config="sparepartConfig"
        @success="initialize"
        @close="singleOptDialogVisible=false"
      ></stock-single-opt-dialog>

      <el-dialog :visible.sync="safetyStockDialog" width="900px">
        <div slot="title">
          <span class="el-dialog__title">{{ $t('part.text65') }}</span>

          <el-tooltip class="item" effect="dark" :content="$t('part.text66')" placement="bottom-start">
            <span><i class="el-icon-question"></i></span>
          </el-tooltip>
        </div>
        <part-set-safety-stock-form v-if="safetyStockDialog" :formdata="formdata" ref="setSafetyStockForm"></part-set-safety-stock-form>
        <div slot="footer" class="dialog-footer">

          <el-button type="ghost" @click="safetyStockDialog = false" >{{ $t('common.base.cancel') }}</el-button>
          <el-button type="primary" @click="updateSafetyStock" :disabled="pending" >{{ $t('common.base.makeSure') }}</el-button>

        </div>
      </el-dialog>

      <el-dialog class="part-info-dialog" :title="$t('part.detail.text1')" :visible.sync="partInfoDialog" width="600px">
        <div class="part-info-panel">
          <div class="page-panel-body" v-if="partInfo">
            <div class="page-row">
              <div class="page-row-left">{{$t('common.label.serialNumber')}}</div>
              <div class="page-row-right">{{partInfo.serialNumber}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('common.base.name')}}</div>
              <div class="page-row-right">{{partInfo.name}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('common.part.category')}}</div>
              <div class="page-row-right">{{partInfo.type}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('common.part.specifications')}}</div>
              <div class="page-row-right">{{partInfo.standard}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('common.label.unit')}}</div>
              <div class="page-row-right">{{partInfo.unit}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('product.component.miniTable.partType.salePrice')}}</div>
              <div class="page-row-right">{{partInfo.salePrice}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('common.part.explain')}}</div>
              <div class="page-row-right">{{partInfo.description}}</div>
            </div>
            <div class="page-row row-image">
              <div class="page-row-left label-image">{{$t('common.base.image')}}</div>
              <div class="page-row-right content-image">
                <template v-if="Array.isArray(partInfo.imageGroup) && partInfo.imageGroup.length > 0">
                  <base-file-item class="part-image-base" v-for="(item, index) in partInfo.imageGroup" :source="partInfo.imageGroup" :key="index" :file="item" readonly/>
                </template>
                <template v-else-if="Array.isArray(partInfo.imageList) && partInfo.imageList.length > 0">
                  <img class="part-image" v-for="(img, idx) in partInfo.imageList" :key="idx" :src="img" @click="preview(img,partInfo.imageList)">
                </template>
                <template v-else-if="partInfo.image">
                  <img class="part-image" :src="partInfo.image" @click="preview(partInfo.image)">
                  <!-- <img class="part-image" :src="partInfo.image" alt="备件图片"> -->
                </template>
              </div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('common.base.state')}}</div>
              <div class="page-row-right">{{partInfo.enable == 1 ? $t('common.paas.buttons.enable') : $t('common.paas.buttons.disable')}}</div>
            </div>
            <div class="page-row">
              <div class="page-row-left">{{$t('customer.detail.customerProductTable.table.label.createTime')}}</div>
              <div class="page-row-right">{{partInfo.createTime | fmt_datetime}}</div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="partInfoDialog = false" :disabled="pending" >{{ $t('common.base.makeSure') }}</el-button>
        </div>
      </el-dialog>

      <!-- start 导入备件库存 -->
      <base-import
        v-if="allowImportAndExport"
        title="导入"
        ref="importStock"
        :action="repertoryStockViewImport"
        :template-url="`${partRepertoryStockViewImportTem}?withSerialNumber=${withSerialNumber}`"
      >
      </base-import>
      <!-- start 导入备件库存 -->


      <base-export1 ref="exportPanel" 
                   v-if="allowImportAndExport"
                   :columns="filterColumns"
                   :action="partRepertoryStockViewExport"
                   :method="'post'"></base-export1>
    </div>


    <base-panel :show.sync="multipleSelectionPanelShow" width="420px">
      <h3 slot="title" style="display: flex;justify-content: space-between;align-items: center">
        <span>{{ $t('common.base.exportModal.selectedData', {count:selected.length}) }}</span>
        <span v-if="selected.length" class="part-panel-btn" @click="toggleSelection()" :title="$t('task.taskTypes.archive.clearChoseData')" data-placement="right" v-tooltip></span>
      </h3>

      <div class="part-selected-panel">
        <div class="part-selected-tip" v-if="!selected.length">
          <img :src="noDataImage">
          <p>{{ $t('product.productType.tips.tip3') }}</p>
        </div>
        <template v-else>
          <div class="part-selected-list">
            <div class="part-selected-row part-selected-head">
              <span class="part-selected-sn">{{ $t('common.label.serialNumber') }}</span>
              <span class="part-selected-name">{{ $t('common.form.type.subSparePart') }}</span>
            </div>
            <div class="part-selected-row" v-for="c in selected" :key="c.id">
              <span class="part-selected-sn">{{c.sparepart.serialNumber}}</span>
              <span class="part-selected-name">{{c.sparepart.name}}</span>
              <button type="button" class="part-selected-delete" @click="cancelSelectPart(c)">
                <i class="iconfont icon-fe-close"></i>
              </button>
            </div>
          </div>
        </template>
      </div>
    </base-panel>


  </div>
</template>

<script>
// pageDes 备件库存列表
import _ from 'lodash';
import qs from '@src/util/querystring2';
import Page from '@src/model/Page';
import PartSetSafetyStockForm from './form/PartSetSafetyStockForm.vue';
import BaseSearchDrawer from 'packages/BaseSearchDrawer/BaseSearchDrawer.vue';
import StockBatchOptDialog from './components/StockBatchOptDialog';
import StockSingleOptDialog from './components/StockSingleOptDialog';

import { formatDate, useDatePicker, objectDateToTimestamp } from 'pub-bbx-utils';
import AuthUtil from '@src/util/auth';
import StorageUtil from '@src/util/storageUtil';
import { checkButtonDisplayed } from '@src/util/dom';
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import { pageSparepartStock } from 'pub-bbx-global/pageType/dist'
import { sessionStorageGet, sessionStorageRemove } from '@src/util/storageV2'

import { isStandardEdition, isExperienceEdition, isEnterpriseEdition } from '@shb-lib/version'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import { VersionControlSparePartMixin } from '@src/mixins/versionControlMixin'

/* export & import */
import { partRepertoryStockViewExport } from '@src/api/Export';
import { partRepertoryStockViewImportTem, repertoryStockViewImport } from '@src/api/Import';

import TableForStashWidth from '@src/mixins/tableForStashWidth/index.js'
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { defaultTableData } from '@src/util/table'

const STORAGE_COLNUM_KEY = 'repertory_list_column';
const STORAGE_PAGESIZE_KEY = 'repertory_list_pagesize';
import { getOssUrl } from '@src/util/assets'
const noDataImage = getOssUrl('/no_data.png')
import { t } from '@src/locales'

export default {
  name: 'part-stock-view',
  inject: ['initData'],
  mixins: [
    VersionMixin, 
    ThemeMixin, 
    TableForStashWidth,
    VersionControlSparePartMixin
  ],
  data(){
    let pageSize = StorageUtil.get(STORAGE_PAGESIZE_KEY) || 10;
    let originModel = {
      keyWord: '',
      type: '',
      enable: '',
      pageNum: 1,
      pageSize,
      sortBy: {},
      isMissingPart: 0,
      description: '', // 说明
      standard:'', // 规格
      repertoryTypeList: [], // 仓库分类
      productTypeList: [], // 关联产品类型
    };

    const { nearDate } = useDatePicker()

    return {
      defaultTableData,
      noDataImage,
      isButtonDisplayed: checkButtonDisplayed(),
      selectColumnState: 'partV2_repertoryStockList',
      multipleSelectionPanelShow: false,
      selectedLimit: 500,
      auths: {}, // 权限对象
      isPersonalRepertory: false, // 是否开启个人备件库
      userId: '', // 当前登录用户的Id
      tagIds: [], // 当前用户所属团队
      tagIdsWithChildTag: [],
      types: [],
      productType: [],
      
      columns: [],
      isExpand: false,
      pending: false,
      sparepart: {
        sparepartId: '',
        loading: false,
        options: []
      },
      
      
      originModel,
      model: _.assign({}, originModel),

      page: new Page(),
      selected: [],

      batchOptDialogVisible: false,
      batchOptRepertories: [],
      batchOptRepertory: [],
      batchOptType: '',
      singleOptDialogVisible: false,
      singleOptType: '',

      instockDialog: false,
      outstockDialog: false,
      instockBatchDialog: false,
      outstockBatchDialog: false,
      transferBatchDialog: false,
      applyDialog: false,
      allocationDialog: false,
      partInfoDialog: false,
      safetyStockDialog: false,
      repertory:[],
      repertorySelected:'',
      sparepartConfig:{},
      formdata: {},
      repertoryName:'',
      partInfo: null,
      dialogLoadingInstance: null,

      pickerOptions2: {
        shortcuts: [
          nearDate(t('common.base.aboutTime.nearlyWeek'), 1, 'week'),
          nearDate(t('common.base.aboutTime.nearlyMonth'), 1, 'month'),
          nearDate(t('common.base.aboutTime.lastThreeMonths'), 3, 'month'),
        ]
      },
      timeValue: '',

      repertories: [], // 所有可见的仓库
      withSerialNumber: false,
      isManage: false, // 仓库报表按钮是否可见
      isPartSparesDialog: false, // 审批弹窗
      isPartSparesBatchDialog: false, // 批量审批弹窗
      openSuperCodePro: true, // 是否开启超级二维码
      partRepertoryStockViewExport,
      partRepertoryStockViewImportTem,
      repertoryStockViewImport,
      pageLoading:true,
      tableContainerHeight:'440px',
    }
  },
  computed: {
    // 是否允许导入导出
    allowImportAndExport(){
      return this.allowImport || this.allowExport
    },
    allowImport() {
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_STOCK_IMPORT')
    },
    allowExport() {
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_STOCK_EXPORT')
    },
    // 是否有编辑权限
    allowEdit(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_EDIT');
    },
    allowInout(){
      return AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_INOUT');
    },
    /**
     * 满足以下调价可申领备件
     * 
     * 1. 开启个人备件库
     * 2. 拥有【个人备件库】权限
     */
    allowApply(){
      return this.isPersonalRepertory !== false && AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_PERSION');
    },

    /**
     * 所有可见的仓库
     * 
     * 满足以下条件可见：
     * 1. 仓库没有设置可见范围
     * 2. 仓库可见范围包括自己
     * 3. 是仓库管理员
     */
    visibleRepertories(){
      let arr = Array.isArray(this.repertories) ? this.repertories : [];
      return arr.filter(item => {
        return null == item.teamIds
          || !item.teamIds.length // 不限制团队
          || item.teamIds.some(team => this.tagIdsWithChildTag.indexOf(team.id) >= 0) // 团队一员
          || item.manager.some(m => m.userId === this.userId); // 仓库管理员
      });
    },
    /**
     * 所有可操作的仓库
     *  
     * 以下情况能够进行出入库操作
     * 1. 管理员为空
     * 2. 管理员中包含自己
     */
    manageRepertories(){
      let arr = Array.isArray(this.repertories) ? this.repertories : [];

      return arr.filter(item => {
        return null == item.manager 
          || item.manager.length == 0 
          || item.manager.some(item => item.userId == this.userId);
      })
    },
    /**
     * 查看仓库报表权限
     * */
    viewReport() {
      return this.allowInout && !!this.auths.VIP_REPORT_VIEW;
    },
    filterColumns() {
      return this.columns.filter(c => c.label);
    },
    // 是否显示 备件调拨
    isShowPartTransfer() {
      return this._isShowPartTransfer
    },
    // 是否显示 备件申领
    isShowPartApply() {
      return this._isShowPartApply
    },
    isShowMoreSperaParts() {
      return this._isShowMoreSpareParts
    },
    isStandardEdition() {
      return isStandardEdition()
    },
    isExperienceEdition() {
      return isExperienceEdition()
    },
    isEnterpriseEdition() {
      return isEnterpriseEdition()
    },
    // 是否允许导出
    isAllowExport() {
      return this.allowInout && this.allowExport && this.isButtonDisplayed
    },
    // 是否允许导入
    isAllowImport() {
      return !this.isExperienceEdition && this.allowInout && this.allowImport && this.isButtonDisplayed
    },
    isShowRepertorySelect() {
      // 企业版
      if (this.isEnterpriseEdition) {
        return true
      }
      // 标准版
      if (this.isStandardEdition) {
        return false
      }
      // 体验版
      if (this.isExperienceEdition) {
        return false
      }
      // 其他
      return true
    },
  },
  methods: {
    // 查看产品类型详情
    openProductMenuTab(id) {
      let fromId;
      try {
        fromId = window.frameElement.getAttribute('id');
      } catch (error) {

      }
      // this.$platform.openTab({
      //   id: `productV2_catalog_view_${id}`,
      //   title: '产品类型详情',
      //   close: true,
      //   url: `/productV2/catalog/view?id=${id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductV2CatalogView,
        key: id,
        params: `id=${id}`,
        fromId
      })
    },
    /**
     * @description: 点击批量 出库/入库/调拨/分配 按钮
     * @param {String} type batchOutStock/batchInStock/batchTransfer/batchSpare
     */
    btnToBatchOperate(type) {
      if(!this.allowInout){
        this.$platform.alert(t('part.tips84'));
        return
      }
      let { status, message } = this.judgeSelectManager();
      let isSucc = (status == 0);

      if(!isSucc) {
        return this.$platform.alert(message);
      }

      let data = this.selected.filter(item => {
        return type === 'batchTransfer' ? item.repertoryCount && this.allowInOutStore(item) : this.allowInOutStore(item)
      });

      switch (type) {
      case 'batchOutStock':
        this.batchOptRepertories = []
        this.batchOptRepertory = []
        break;
      case 'batchInStock':
        this.batchOptRepertories = []
        this.batchOptRepertory = this.manageRepertories
        break;
      case 'batchTransfer':
        this.batchOptRepertories = []
        this.batchOptRepertory = this.visibleRepertories
        break;
      case 'batchSpare':
        this.batchOptRepertories = this.repertories
        this.batchOptRepertory = this.manageRepertories
        break;
      default:
        break;
      }
      this.batchOptType = type
      this.batchOptDialogVisible = true;

      this.$refs.stockBatchOptDialog.formReceiveData(`${type}Form`, data, this.userId);
    },

    /**
     * @description: 点击单个 出库/入库/调拨/分配/申领 按钮
     * @param {String} type outStock/allocation/spare/apply
     */
    btnToSingleOperate(type, value) {
      // 出库、入库、调拨 权限限制
      if(!this.allowInout && (type === 'outStock' || type === 'inStock' || type === 'allocation')){
        this.$platform.alert(t('part.tips84'));
        return
      }
      // 申领 权限限制
      if(!this.allowApply && type === 'apply') return;

      this.pending = false;
      // 打开弹窗
      this.singleOptType = type
      this.singleOptDialogVisible = true;

      if (type === 'allocation') { // 调拨赋值
        this.$refs.stockSingleOptDialog.allocationFormInit(value, this.visibleRepertories, this.sparepartConfig, this.userId)
      } else { // 其他赋值
        this.formdata = value
      }
    },

    // 关闭高级搜索弹框
    closeDrawer(){
      this.isExpand = false;
    },
    cancelSelectPart(part) {
      if (!part || !part.id) return;
      this.selected = this.selected.filter(ms => ms.id !== part.id);
      this.toggleSelection([part]);
    },
    toggleSelection(rows) {
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for(let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.page.list.every(item => {
            return item.id !== row.id;
          })
          if(isNotOnCurrentPage) return
        }
        rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.clearSelection();
        this.selected = [];
      }
    },
    // select part
    handleSelection(selection) {
      let tv = this.computeSelection(selection);
      // 在需要限制最多选择500个备件时，取消function内部全部注释即可
      let original = this.selected
        .filter(ms => this.page.list.some(cs => cs.id === ms.id));
      let unSelected = this.page.list
        .filter(c => original.every(oc => oc.id !== c.id));

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.table.toggleRowSelection(row, false);
            })
            : this.$refs.table.clearSelection();
        })
        return this.$platform.alert(t('common.base.tip.maxDataCanChooseTips', {data1:this.selectedLimit}));
      }
      this.selected = tv;

      this.$refs.baseSelectionBar?.openTooltip();
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    computeSelection(selection) {
      let tv = [];
      tv = this.selected
        .filter(ms => this.page.list.every(c => c.id !== ms.id));
      tv = _.uniqWith([...tv, ...selection], _.isEqual);
      return tv;
    },
    matchSelected() {
      if (!this.selected.length) return;
      const selected = this.page.list
        .filter(c => {
          if (this.selected.some(sc => sc.id === c.id)) {
            this.selected = this.selected.filter(sc => sc.id !== c.id);
            this.selected.push(c);
            return c;
          }
        }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },

    openStock(){

      // this.$platform.openTab({
      //   id: `stats_part_${this.repertoryName}`,
      //   url: `/stats/sparepart/showStatistics?id=${this.repertoryName}&source=1`,
      //   title: '仓库报表',
      //   close: true,
      //   reload:true
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageStatsPart,
        key: this.repertoryName,
        params: `id=${this.repertoryName}&source=1`,
        reload: true,
      })
    },
    openDialogForSetSafetyStock(selected) {
      // permission granted
      if (!selected || !selected.length) {
        return this.$platform.alert(t('part.text67'));
      }

      if (selected.length > 50) {
        return this.$platform.alert(t('part.text68', {num:50}));
      }

      this.formdata = [];
      let repertoryNames = [];

      for(let i = 0; i < selected.length; i++) {
        let row = selected[i];
        let isManage = this.allowInOutStore(row);

        isManage
          ? this.formdata.push({
            ...row.sparepart,
            repertory: row.repertory.name,
            sparepartRepertoryId: row.id,
            safetyStock: row.safetyStock || '',
          })
          : repertoryNames.push(row.repertory.name);
      }
      // 仓库列表名字去重
      repertoryNames = [...new Set(repertoryNames)];

      if (!this.formdata || !this.formdata.length && repertoryNames.length > 0) {
        return this.$platform.alert(
          t('part.text69', {data1:repertoryNames.join(' ,')})
        );
      }

      this.safetyStockDialog = true;
    },
    async updateSafetyStock() {
      let form = this.$refs.setSafetyStockForm;
      if (!form) return;
      let safetyStock = await form.pack();
      if (!safetyStock) return;

      const updateSafetyStockParams = safetyStock
        .map(p => ({
          id: p.sparepartRepertoryId,
          safetyStock: p.safetyStock,
        }))
        .filter(part => part.safetyStock);

      const cancelSafetyStockParams = safetyStock
        .map(p => ({
          id: p.sparepartRepertoryId,
          safetyStock: p.safetyStock,
        }))
        .filter(part => !part.safetyStock)
        .map(p => {
          p.safetyStock = null;
          return p;
        });

      this.pending = true;
      try {
        let result, cancelResult;
        if (updateSafetyStockParams && updateSafetyStockParams.length) {
          result = await this.$http.post('/partV2/repertory/applyBatchSafetyStocks', updateSafetyStockParams);
        }

        if (cancelSafetyStockParams && cancelSafetyStockParams.length) {
          cancelResult = await this.$http.post('/partV2/repertory/cancelBatchSafetyStocks', cancelSafetyStockParams);
        }

        if((result && result.status === 0) || (cancelResult && cancelResult.status === 0)){
          this.$platform.toast(t('part.text70'));
          this.safetyStockDialog = false;
        }else{
          this.$platform.alert(result.message);
        }
      } catch (e) {
        console.warn(e);
      }
      this.pending = false;
      this.loadData();
    },
    openPartInfoDialog(part) {
      this.partInfoDialog = true;
      if (!this.partInfo || (this.partInfo && this.partInfo.id !== part.id)) {
        this.partInfo = null;
        this.loadPartInfo(part.id);
        this.$nextTick(() => {
          this.dialogLoadingInstance = this.$loading({
            target: '.part-info-panel',
          });
        });
      }
    },
    async loadPartInfo(partId) {
      try {
        let result = await this.$http.get(`/partV2/category/get?id=${partId}`);
        this.dialogLoadingInstance.close();
        if(result?.imageGroup && result.imageGroup.length !== 0) {
          result.imageGroup.forEach(item => {
            this.$set(item, 'filename', item.fileName)
          })
        }
        this.partInfo = result;
      } catch (error) {
        console.log(error)
      }
    },
    // 导出库存记录
    exportData(exportAll){
      if(!this.isAllowExport) return;
      let ids = [];

      if(!exportAll){
        if(this.selected.length == 0) return this.$platform.alert(t('common.base.tip.exportUnChooseTip'));
        ids = this.selected.map(item => item.id);
      }
      
      this.$refs.exportPanel.open(ids, `${formatDate(new Date(), 'YYYY-MM-DD')}备件库存记录.xlsx`);
    },
    importSucc(){
      this.loadData();
    },
    importStock(){
      if(!this.isAllowImport) return;
      let instance = this.$refs.importStock;
      instance.open();
    },
    // 备件图片预览
    preview(url, urls){
      this.$previewElementImg(url, urls)
      // BaseGallery.preview(event.currentTarget);
    },
    isEnableSparePart(row){
      let part = row.sparepart || {};
      return part.enable == 1;
    },
    /**
     * 判断当前用户能够对指定库存进行出入库操作
     * 根据仓库的管理是否为当前用户判断
     *  
     * 以下情况能够进行出入库操作
     * 1. 管理员为空
     * 2. 管理员中包含自己
     * 
     * @author dongls
     */
    allowInOutStore(row){
      let repertory = row.repertory || {};
      let manager = repertory.manager || [];
      return null == manager || manager.length == 0 || manager.some(item => item.userId == this.userId);
    },
    chooseColnum(column){
      this.trackEventHandler('selectColumn');

      column.show = !column.show;
      this.saveColumnStatusToStorage();
      // let data = {};
      // this.filterColumns.forEach(item => data[item.field] = item.show)
      // StorageUtil.save(STORAGE_COLNUM_KEY, data);
    },
    seeTime(){
      this.model.timeStart = formatDate(this.timeValue[0])
      this.model.timeEnd = formatDate(this.timeValue[1])
    },
    openDetail(row){
      // this.$platform.openTab({
      //   id: `partV2_detail_${row.id}`,
      //   url:`/partV2/detail?id=${row.id}`,
      //   title: '备件品类详情'
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePartV2Detail,
        key: row.id,
        params: `id=${row.id}`,
      })
    },
    select(data){
      this.selected = data;
    },
    create(){
      // this.$platform.openTab({
      //   id: 'partV2_create',
      //   url: '/partV2/create',
      //   title: '创建备件品类'
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreatePartV2,
      })
    },
    
    jump(pageNum){
      this.model.pageNum = pageNum;
      this.loadData();
    },
    pageSizeChange(pageSize){
      this.model.pageSize = pageSize;
      this.originModel.pageSize = pageSize;
      
      this.loadData();

      // 存入localStorage
      StorageUtil.save(STORAGE_PAGESIZE_KEY, pageSize);
    },
    search(){
      this.isExpand = false;
      this.trackEventHandler('search')
      this.model.pageNum = 1;
      this.loadData();
    },
    reset(){
      this.isExpand = false;
      this.model = _.assign({}, this.originModel);
      this.sparepart.sparepartId = '';
      this.$refs.table.clearSort();
      this.loadData();
    },
    sort({column, prop, order}){
      let sortBy = {};

      if(prop){
        let tableName = 'repertorySparepart';
        let key = `${tableName}.${prop}`
        sortBy[key] = order == 'ascending';
      }
      
      this.model.sortBy = sortBy;
      this.loadData();
    },
    async loadData(msg){
      this.pageLoading = true;
      if(msg) this.model.pageNum = 1;
      try{
        this.page = await this.fetchData();
        // this.model.pageNum = this.page.pageNum;
        this.model.pageSize = this.page.pageSize;

        this.matchSelected();
      }catch(error){
        console.log(error)
      }
      this.pageLoading = false;
    },
    fetchData(){
      // 获取库存列表
      const params = objectDateToTimestamp({...this.model}, ['timeStart', 'timeEnd'])
      return this.$http.post('/partV2/repertory/list', params)
    },
    fetchSparepart(keyword){
      // 获取备件
      let model = {
        keyWord: keyword,
        enable: 1,
        pageSize: 50
      }
      this.sparepart.loading = true
      this.$http.post('/partV2/repertory/sparepart/list', model)
        .then(result => this.sparepart.options = result.list)
        .catch(err => console.log(err))
        .finally(() => this.sparepart.loading = false);
    },
    chooseRepertory(value){
      this.repertoryName = value;
      if(value){
        this.model.repertoryId = value
      }else{
        delete this.model.repertoryId
      }
      this.model.pageNum = 1;
      this.loadData();
      if(this.manageRepertories.length == 0) return this.isManage = false;
      let flag = this.manageRepertories.some(item => item.id == value);
      if(value && !flag) return this.isManage = false;
      this.isManage = true;
    },
    chooseSparepart(value){
      if(this.sparepart.sparepartId == value) return;
      this.sparepart.sparepartId = value;
      this.model.sparepartId = value;
    },
    // TODO: 不再异步获取，改为注入参数
    fecthSparepartConfig(){
      // 获取备件设置
      return this.$http.post('/partV2/repertory/sparepartConfig').then(result => {
        this.sparepartConfig = result
      })
    },

    async removestockBatch(value){
      // sparepart.name
      let val = this.selected;
      let remove = []
      let ids = []
      if(val.length > 0){
        let message = [];
        
        for(let i = 0;i < val.length;i++){
          let repe = val[i];
          // 确定该库存能否被删除
          let notAllow = true;
          // 判断仓库是否存在
          notAllow = notAllow && repe.repertory && repe.repertory.id && repe.repertory.name != null;
          // 判断备件是否存在
          notAllow = notAllow && repe.sparepart && repe.sparepart.id;
          // 判断是否有库存
          notAllow = notAllow && repe.repertoryCount > 0;

          if(notAllow){
            message.push(t('part.text71', {data1:repe.sparepart.name}));
            continue;
          }
          
          if(repe.sparepart && repe.sparepart.name) remove.push(`【${ repe.sparepart.name }】`)
          ids.push(repe.id);
        }

        if(message.length > 0){
          return this.$platform.alert(message.join('\n'));
        }

        try {
          if(!await this.$platform.confirm(t('part.text72', {remove}))) return;
          this.pending = true;
          let result = await this.$http.post('/partV2/repertory/batchRemove', ids)
          if(result.status == 0){
            this.$platform.toast(t('common.base.removeSuccess')).then(() => this.initialize());
            this.toggleSelection();
          }else{
            this.$platform.alert(result.message);
          }
        } catch (error) {
          console.log(error)
        }
        this.pending = false;
      }else{
        this.$platform.alert(t('part.text73'));
      }
    },

    buildParams(pageNum, pageSize){
      return {
        ...this.model,
        pageNum,
        pageSize
      };
    },

    // 获取仓库列表
    fetchRepertory(){
      this.$http.get('/partV2/repertory/allRepertory')
        .then(result => {
          this.repertories = result || []
          if(this.manageRepertories.length > 0) this.isManage = true;
        })
        .catch(err => console.warn(err))
    },
    initialize(){      
      this.fetchRepertory();
      this.fecthSparepartConfig();
      this.fetchSparepart();
      this.findFastPageData().then(()=>{
        this.loadData();
      });
      window.addEventListener('message', (event)=> {
        const {action, data} = event.data;
        if (action == 'shb.frame.fasterPage'){
          const {data:parseData, type} = data;
          if(type == `bbx-faster-${pageSparepartStock.type}`){
            this.findFastPageData(parseData);
          }
        }
      });
      
    },
    buildColumns(){
      let localData = StorageUtil.get(STORAGE_COLNUM_KEY) || {};

      let columns = [
        {
          label: t('common.label.serialNumber'),
          field: 'serialNumber',
          show: true,
          width: '170px',
          exportAlias: 'sparepart.serialNumber',
          tooltip: true,
          export: true,
        },
        {
          label: t('common.base.name'),
          field: 'name',
          show: true,
          exportAlias: 'sparepart.name',
          tooltip: true,
          export: true,
        },
        {
          label: t('common.label.sparepartType'),
          field: 'type',
          show: true,
          tooltip: true,
          export: true,
        },
        {
          label: t('common.label.sparepartStandard'),
          field: 'standard',
          show: true,
          exportAlias: 'sparepart.standard',
          tooltip: true,
          export: true,
        },
        {
          label: t('common.label.unit'),
          field: 'unit',
          exportAlias: 'sparepart.unit',
          show: false,
          width: 100,
          exportNoChecked: true,
          export: true,
        },
        {
          label: t('common.base.explain'),
          field: 'description',
          exportAlias: 'sparepart.description',
          tooltip: true,
          show: true,
          width: 150,
          export: true,
        },
        {
          label: t('common.base.warehouse'),
          field: 'repertory',
          show: true,
          exportAlias: 'repertory.name',
          tooltip: true,
          export: true,
        },
        {
          label: t('part.text74'),
          field: 'repertoryType',
          show: true,
          exportAlias: 'repertory.type',
          tooltip: true,
          export: true,
        },
        {
          label: t('part.text9'),
          field: 'safetyStock',
          show: false,
          exportAlias: 'safetyStock',
          tooltip: true,
          export: true,
        },
        {
          label: t('common.form.preview.materialVerifyEliminate.count'),
          field: 'repertoryCount',
          width: '130px',
          show: true,
          sortable: 'custom',
          tooltip: true,
          export: true,
        },
        {
          label: t('common.label.operate'),
          field: 'operate',
          width: '250px',
          minWidth: '160px',
          show: true,
          export: false,
          fixed: 'right',
          tooltip: true,
        },
        {
          label: t('part.components.partStock.text2'),
          field: 'isWarring',
          width: '250px',
          minWidth: '160px',
          show: false,
          export: true,
          tooltip: true,
        }
      ];
      
      if(this.openSuperCodePro) {
        // 如果开启超级二维码，需要添加关联产品类型
        let proIndex = columns.indexOf(columns.filter(item=>item.field === 'repertory')[0])
        let pro = {
          label: t('product.setting.qrCodeSet.associateDialog.btn1'),
          field: 'productTypeList',
          exportAlias: 'catalogId',
          tooltip: true,
          show: false,
          width: 150,
          exportNoChecked: true,
          export: true,
        }
        
        if(proIndex != -1) columns.splice(proIndex, 0, pro)
      }
      columns.forEach(column => {
        let isShow = localData[column.field];
        if(typeof isShow == 'boolean') column.show = isShow;
      })

      return columns;
    },
    /**
     * 判断是否是管理员 并返回
    */
    judgeSelectManager() {
      let repertoryNames = [];
      let managers = [];

      for(let i = 0; i < this.selected.length; i++) {
        let row = this.selected[i];
        let isManage = this.allowInOutStore(row);

        isManage
          ? managers.push(row.repertory.name)
          : repertoryNames.push(row.repertory.name);
      }
      // 仓库列表名字去重
      repertoryNames = [...new Set(repertoryNames)];

      return (
        Array.isArray(repertoryNames) && repertoryNames.length > 0 && managers.length == 0
          ? {
            status: 1,
            succ: true,
            data: repertoryNames,
            message: t('part.text69', {data1:repertoryNames.join(' ,')})
          }
          : {status: 0}
      );
    },
    trackEventHandler(type) {
      switch (type) {
      case 'stockTable':
        this.$tdOnEvent('pc：备件库存-仓库报表事件');
        break;
      case 'search':
        this.$tdOnEvent('pc：备件库存-搜索事件');
        break;
      case 'reset':
        this.$tdOnEvent('pc：备件库存-重置事件');
        break;
      case 'advSearch':
        this.$tdOnEvent('pc：备件库存-高级搜索事件');
        break;
      case 'chooseRepertory':
        this.$tdOnEvent('pc：备件库存-仓库筛选下拉框事件');
        break;
      case 'switchPart':
        this.model && this.model.isMissingPart === 0 && this.$tdOnEvent('pc：备件库存-全部备件事件');
        this.model && this.model.isMissingPart === 1 && this.$tdOnEvent('pc：备件库存-库存提醒事件');
        break;
      case 'remove':
        this.$track.clickStat(this.$track.formatParams('REMOVE_STOCK'));
        this.$tdOnEvent('pc：备件库存-移除事件');
        break;
      case 'outStock':
        this.$track.clickStat(this.$track.formatParams('BATCH_OUT_STOCK', null ,'OUT_STOCK'));
        this.$tdOnEvent('pc：备件库存-出库事件');
        break;
      case 'inStock':
        this.$track.clickStat(this.$track.formatParams('BATCH_IN_STOCK', null ,'IN_STOCK'));
        this.$tdOnEvent('pc：备件库存-入库事件');
        break;
      case 'transfer':
        this.$track.clickStat(this.$track.formatParams('BATCH_TRANSFER_STOCK', null ,'TRANSFER_STOCK'));
        this.$tdOnEvent('pc：备件库存-调拨事件');
        break;
      case 'spare':
        this.$track.clickStat(this.$track.formatParams('BATCH_DISTRIBUTE_STOCK', null ,'DISTRIBUTE_STOCK'));
        this.$tdOnEvent('pc：备件库存-分配事件');
        break;
      case 'setSafeStock':
        this.$track.clickStat(this.$track.formatParams('SET_SAFETY_STOCK'));
        this.$tdOnEvent('pc：备件库存-设置安全库存事件');
        break;
      case 'selectColumn':
        this.$tdOnEvent('pc：备件库存-选择列事件');
        break;
      default:
        break;
      }
    },
    tableTrackEventHandler (type) {
      switch (type) {
      case 'outStock':
        this.$track.clickStat(this.$track.formatParams('SINGLE_OUT_STOCK', null ,'OUT_STOCK'));
        this.$tdOnEvent('pc：备件库存-列表出库事件');
        break;
      case 'inStock':
        this.$track.clickStat(this.$track.formatParams('SINGLE_IN_STOCK', null ,'IN_STOCK'));
        this.$tdOnEvent('pc：备件库存-列表入库事件');
        break;
      case 'allocation':
        this.$track.clickStat(this.$track.formatParams('SINGLE_TRANSFER_STOCK', null ,'TRANSFER_STOCK'));
        this.$tdOnEvent('pc：备件库存-列表调拨事件');
        break;
      case 'spare':
        this.$track.clickStat(this.$track.formatParams('SINGLE_DISTRIBUTE_STOCK', null ,'DISTRIBUTE_STOCK'));
        this.$tdOnEvent('pc：备件库存-列表分配事件');
        break;
      case 'apply':
        this.$track.clickStat(this.$track.formatParams('APPLY_STOCK'));
        this.$tdOnEvent('pc：备件库存-列表申领事件');
        break;
      default:
        break;
      }
    },
    
    // 构建表格列
    buildTableColumn() {
      let baseColumns = this.buildColumns();
      const localStorageData = this.getLocalStorageData();
      let columnStatus = (localStorageData.columnStatus && localStorageData.columnStatus[this.selectColumnState]) || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let columns = [...baseColumns].map(col => {
        let show = col.show;
        let width = col.width;
        let localField = localColumns[col.field];
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';

        return col;
      });

      if (this.isBasicEditionHideProduct) {
        columns = columns.filter(item => item.field !== 'esProductEntities')
      }

      return columns;
    },
    /**
     * @des 提供给快捷筛选视图的方法
     */
    fasterFilterList(keyObj){
      try {
        let arr_ = [];
        for(let key in keyObj){
          let value = keyObj[key];
          this.model[key] = value;
        }
        Promise.all(arr_).then(()=>{
          this.loadData('changeTab');
        })
      } catch (error) {
        console.warn(error, 'fasterFilterList error try catch');
      }
    },
    /**
     * @des 查询是否有查询参数
     */
    findFastPageData(data){
      return new Promise((resolve, reject)=>{
        try {
          let parseData = sessionStorageGet(`bbx-faster-${pageSparepartStock.type}`);
          if(parseData){
            sessionStorageRemove(`bbx-faster-${pageSparepartStock.type}`);
          }
          if(!data && !parseData) return resolve()
          const {filterData} = data || JSON.parse(parseData);
          this.fasterFilterList(filterData);
        } catch (error) {
          console.warn(error, 'findFastPageData error try catch');
          resolve()
        }
      })
    },
    /**
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        // selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 20 - 12 ;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        console.log(min, 'min')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    }
  },
  mounted(){
    let initData = _.cloneDeep(this.initData) || {};

    this.types = _.cloneDeep(initData.sparepartType) || [];
    this.auths = _.cloneDeep(initData.auths) || {};
    this.isPersonalRepertory = _.cloneDeep(initData.isPersonalRepertory);
    this.userId = _.cloneDeep(initData.userId) || '';
    this.tagIds = _.cloneDeep(initData.tagIds) || [];
    this.tagIdsWithChildTag = _.cloneDeep(initData.tagIdsWithChildTag) || [];
    this.productType = _.cloneDeep(initData.productType) || [];
    this.openSuperCodePro = initData.openSuperCodePro !== false;

    let urlParams = qs.parse(window.location.search);
    if(urlParams.id){
      this.repertoryName = urlParams.id;
      this.model.repertoryId = urlParams.id
    }else{
      delete this.model.repertoryId
    }
    if(urlParams.miss) {
      this.model.isMissingPart = 1;
    }
    this.columns = this.buildTableColumn();
    if(urlParams && urlParams.name){
      this.model.keyWord = urlParams.name
    }
    this.initialize();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
    
  },
  components: {
    [PartSetSafetyStockForm.name]: PartSetSafetyStockForm,
    [BaseSearchDrawer.name]:BaseSearchDrawer,
    [StockBatchOptDialog.name]:StockBatchOptDialog,
    [StockSingleOptDialog.name]:StockSingleOptDialog,
  }
}
</script>

<style lang="scss">
.no-padding{
  padding:0;
}

.has-tag {
  width: calc(100% - 60px);
  overflow: hidden;
}

.tag-position {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
}

.part-option{
  margin: 5px 0;

  p{
    overflow: hidden;
    margin: 0;
    line-height: 24px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

  .part-info-panel {
    min-height: 360px;
  }
  .part-info-dialog {
    .part-info-panel {
      height: 400px;
      overflow: auto;
    }

    .part-info-dialog-img {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      img {
        width: inherit;
        padding: 5px;
      }
    }

    .part-image {
      display: block;
      max-width: 128px;
      max-height: 128px;
      cursor: pointer;
    }
    .row-image {
      flex-wrap: nowrap;
      .label-image {
        flex-shrink: 0;
      }
      .content-image {
        overflow-x: hidden;
      }
      .part-image-base {
       .base-file-info-name{
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: block;
        }
        span {
          color: $text-color-secondary;
        }
      }
    }
  }
  .part-spares-batch-dialog {
    .el-dialog {
      width: 85vw;
      min-width: 950px;
    }
  }

  .srp-user-item{
    display: flex;
    flex-flow: row nowrap;
    align-items: center;
    padding: 4px 0;

    &:last-child{
      margin: 0;
    }

    img{
      display: block;
      width: 28px;
      height: 28px;
      border-radius: 2px;
    }

    p{
      flex: 1;
      margin: 0;
      margin-left: 10px;
      font-weight: 500;
      font-size: 14px;
      overflow: hidden;
      line-height: 28px;
    }
  }

  .dialog-title-tip {
    color: #6c6c6c;
    margin: 5px 0 0 0;
    font-size: 12px;
  }

  // superscript
.part-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 43px;
    line-height: 43px !important;
    a,
    button {
      display: inline-block;
      height: 43px;
      line-height: 43px;
    }
  }
}

// -------- part selected panel --------
.part-selected-count {
  @include fontColor();
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}

.part-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .part-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 160px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: $text-color-regular;
      margin: 8px 0 0 0;
      line-height: 20px;
    }
  }

  .part-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .part-selected-row {
      display: flex;
      flex-flow: row nowrap;
      line-height: 36px;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .part-selected-delete {
          visibility: visible;
        }
      }
    }

    .part-selected-head {
      background-color: #F0F5F5;
      color: #333;
      font-size: 14px;
    }

    .part-selected-sn {
      padding-left: 10px;
      width: 150px;
      @include text-ellipsis;
    }

    .part-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .part-selected-delete {
      width: 36px;
    }

    .part-selected-row button.part-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646B78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

.part-panel-btn {
  float: right;
  cursor: pointer;
  width: 16px;
  height: 16px;
  background: url("../../../assets/img/clear.png") no-repeat center;
  background-size: cover;

  &:hover {
    background: url("../../../assets/img/clear-hover.png") no-repeat center;
    background-size: cover;
  }
}


</style>

<style lang="scss" scoped>
::v-deep .el-radio-group label {
  margin-bottom: 0;
}

::v-deep .el-table th > .cell{
  display: flex;
}
.advanced-search-visible-btn{
  color:$color-primary;
}

::v-deep .el-radio-button:first-child{
  ::v-deep .el-radio-button__inner{
    border-radius: 4px 0 0 4px;
  }
}
::v-deep .el-radio-button:last-child{
  ::v-deep .el-radio-button__inner{
    border-radius: 0 4px 4px 0;
  }
}

.srp-list-form-item{
  width: 150px;
  margin: 0 12px;
  ::v-deep .el-input{
    width: inherit !important;

    input{
      width: inherit !important;
      padding-right: 0 !important;
    }
  }
}
.table-primary {
  color: $color-primary;
  text-decoration: none;
  cursor: pointer;
}
</style>
<style lang="scss">
.repertory-chart-button {
  // margin-right: 10px;
  height: 33px;
  line-height: 14px;
}
.page-panel{
  margin-bottom:0;
}
.page{
  overflow:visible;
}
.page-row {
  .page-row-left {
    &::after {
      content: ":";
      position: relative;
      top: -0.5px;
      margin: 0 8px 0 2px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
      'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
      'Noto Color Emoji';
    }
  }
}
</style>
